<template>
  <div class="discover-content-container">
    <div v-if="followingNotes.length === 0" class="empty-follow-container">
      <div class="empty-icon">
        <svg viewBox="0 0 48 48" fill="currentColor">
          <path d="M24 4C12.95 4 4 12.95 4 24C4 35.05 12.95 44 24 44C35.05 44 44 35.05 44 24C44 12.95 35.05 4 24 4ZM24 8C32.84 8 40 15.16 40 24C40 32.84 32.84 40 24 40C15.16 40 8 32.84 8 24C8 15.16 15.16 8 24 8ZM26 16H22V24H14V28H22V36H26V28H34V24H26V16Z"/>
        </svg>
      </div>
      <div class="empty-text">你还没有关注任何用户</div>
      <div class="empty-subtext">关注喜欢的创作者，获取最新动态</div>
    </div>
    <div v-else class="category-content-container">
      <div class="discover-items">
        <div class="discover-item" v-for="note in followingNotes" :key="note.note_id" @click="goToNoteDetail(note)">
          <div class="discover-image">
            <img v-if="note.media_type === 'image'" :src="note.media_url" :alt="note.title">
            <VideoPoster
              v-else-if="note.media_type === 'video'"
              :videoSrc="note.media_url"
              width="100%"
              height="100%"
              :canvasWidth="320"
              :canvasHeight="180"
              @click="goToNoteDetail(note)"
            />
          </div>
          <div class="discover-title">{{note.title}}</div>
          <div class="discover-user">
            <div class="user-info">
              <img :src="note.avatar_url" class="small-avatar" alt="用户头像">
              <span>{{note.nickname}}</span>
            </div>
            <div class="publish-date">
              <svg class="calendar-icon" viewBox="0 0 24 24" fill="currentColor">
                <path d="M19,4H18V2H16V4H8V2H6V4H5C3.9,4 3,4.9 3,6V20C3,21.1 3.9,22 5,22H19C20.1,22 21,21.1 21,20V6C21,4.9 20.1,4 19,4M19,20H5V10H19V20M19,8H5V6H19V8Z"/>
              </svg>
              <span class="date">{{ formatDate(note.updated_at || note.create_time) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import VideoPoster from '@/components/VideoPoster.vue';

export default {
  name: 'FollowContent',
  components: {
    VideoPoster
  },
  setup() {
    const router = useRouter();
    const followingNotes = ref([]);
    
    // 格式化日期为YYYY-MM-DD格式
    const formatDate = (timestamp) => {
      if (!timestamp) return '未知日期';
      
      try {
        const date = new Date(timestamp);
        
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          return '未知日期';
        }
        
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        
        return `${year}-${month}-${day}`;
      } catch (error) {
        console.error('日期格式化错误:', error);
        return '未知日期';
      }
    };

    // 跳转到笔记详情页
    const goToNoteDetail = (note) => {
      router.push({
        path: '/mecont',
        query: {
          userId: note.user_id,
          noteId: note.note_id
        }
      });
    };
    
    // 获取关注页的笔记数据
    const fetchFollowingNotes = async () => {
      try {
        // 从当前用户的关注API获取关注列表
        const currentUserId = localStorage.getItem('user_id');
        if (!currentUserId) {
          console.error('未找到当前用户ID');
          followingNotes.value = [];
          return;
        }
        
        // 获取当前用户的关注列表
        const followingResponse = await axios.get(`http://1.14.98.17:8765/api/profile/${currentUserId}/following`);
        if (!followingResponse.data.success) {
          console.error('获取关注列表失败');
          followingNotes.value = [];
          return;
        }
        
        const followedUsers = followingResponse.data.data.following || [];
        
        if (followedUsers.length === 0) {
          followingNotes.value = [];
          return;
        }
        
        // 获取所有笔记
        const notesResponse = await axios.get('http://1.14.98.17:8765/api/notes');
        if (!notesResponse.data.success) {
          console.error('获取笔记列表失败');
          return;
        }
        
        // 筛选出关注用户发布的笔记
        const followingUserNotes = notesResponse.data.data.filter(note => 
          followedUsers.includes(note.user_id)
        );
        
        if (followingUserNotes.length === 0) {
          followingNotes.value = [];
          return;
        }
        
        // 按updated_at排序（越近的排在前面）
        const sortedNotes = followingUserNotes.sort((a, b) => {
          const dateA = new Date(a.updated_at || a.create_time);
          const dateB = new Date(b.updated_at || b.create_time);
          return dateB - dateA; // 降序排列，最新的在前面
        });
        
        // 获取每个笔记的媒体和用户信息
        const notesWithDetails = await Promise.all(
          sortedNotes.map(async (note) => {
            try {
              // 获取笔记媒体
              const mediaResponse = await axios.get(`http://1.14.98.17:8765/api/notes/${note.note_id}/media`);
              let mediaUrl = '';
              let mediaType = 'image';
              
              if (mediaResponse.data.success && mediaResponse.data.data.length > 0) {
                const firstMedia = mediaResponse.data.data[0];
                mediaUrl = firstMedia.media_url;
                mediaType = firstMedia.media_type;
              }
              
              // 获取用户信息
              const userResponse = await axios.get(`http://1.14.98.17:8765/api/users/${note.user_id}`);
              let nickname = '匿名用户';
              let avatarUrl = '';
              
              if (userResponse.data.success) {
                nickname = userResponse.data.data.nickname || '匿名用户';
                avatarUrl = userResponse.data.data.avatar_url || '';
              }
              
              // 返回完整的笔记信息
              return {
                ...note,
                media_url: mediaUrl,
                media_type: mediaType,
                nickname: nickname,
                avatar_url: avatarUrl
              };
            } catch (error) {
              console.error(`获取笔记 ${note.note_id} 的详细信息失败:`, error);
              return note;
            }
          })
        );
        
        followingNotes.value = notesWithDetails;
      } catch (error) {
        console.error('获取关注页数据失败:', error);
      }
    };
    
    onMounted(() => {
      fetchFollowingNotes();
      
      // 监听关注状态变化，刷新数据
      window.addEventListener('followStatusChanged', () => {
        fetchFollowingNotes();
      });
    });

    return {
      followingNotes,
      formatDate,
      goToNoteDetail
    };
  }
}
</script>

<style scoped lang="less">
.discover-content-container {
  .empty-follow-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    height: 85vh;
    
    .empty-icon {
      width: 200px;
      height: 200px;
      margin-bottom: 30px;
      color: #ff2442;
      opacity: 0.7;
      
      svg {
        width: 100%;
        height: 100%;
      }
    }
    
    .empty-text {
      font-size: 40px;
      font-weight: bold;
      color: #333333;
      margin-bottom: 20px;
      text-align: center;
    }
    
    .empty-subtext {
      font-size: 30px;
      color: #999999;
      text-align: center;
      max-width: 500px;
      line-height: 1.5;
    }
  }

  .category-content-container {
    padding: 10px;
    
    .discover-items {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      max-width: 760px;
      margin: 0 auto;
      justify-content: space-between;
      
      .discover-item {
        width: calc(50% - 10px);
        height: 660px;
        margin: 10px 0;
        background-color: #fff;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        
        .discover-image {
          position: relative;
          height: 476px;
          overflow: hidden;
          
          img, .video-preview {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
        
        .discover-title {
          width: 100%;
          height: 72px;
          margin: 15px 0 25px 3px;
          font-size: 28px;
          line-height: 1.3;
          font-weight: bold;
          color: #000;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .discover-user {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin: 0 15px;
          
          .user-info {
            display: flex;
            align-items: center;
            
            .small-avatar {
              width: 34px;
              height: 34px;
              border-radius: 50%;
              margin-right: 8px;
            }
            
            span {
              font-size: 24px;
              color: #666;
              max-width: 130px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
          
          .publish-date {
            display: flex;
            align-items: center;
            padding: 5px 10px;
            background-color: rgba(0, 0, 0, 0.03);
            border-radius: 16px;
            
            .calendar-icon {
              width: 20px;
              height: 20px;
              margin-right: 6px;
              color: #666;
            }
            
            .date {
              font-size: 20px;
              color: #666;
              font-weight: 500;
            }
          }
        }
      }
    }
  }
}
</style> 